﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace WindowsFormsApplication
{
    public partial class SyncForm : Form
    {
        public SyncForm()
        {
            InitializeComponent();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (FileSync.CanRun && btnGo.Text == "Go")
            {
                Thread th = new Thread(new ThreadStart(Sync));
                th.IsBackground = true;
                th.Start();
                btnGo.Text = "Pause";
            }
            else if (btnGo.Text == "Go")
            {
                FileSync.CanRun = false;
                btnGo.Text = "Pause";
            }
            else
            {
                FileSync.CanRun = true;
                btnGo.Text = "Go";
            }
        }

        private void Sync()
        {
            FileSync fs = new FileSync();
            SyncDelegate sd = new SyncDelegate(fs.Sync);
            IAsyncResult result = sd.BeginInvoke(txtSource.Text, txtDestination.Text, txtTarget.Text, null, null);
            Thread.Sleep(100);
            result.AsyncWaitHandle.WaitOne();
            sd.EndInvoke(result);
            result.AsyncWaitHandle.Close();
        }


        private void SyncForm_Load(object sender, EventArgs e)
        {
            txtSource.Text = @"D:\WebAmalga_Zbb\AmSrc\webserver\WebAmalga\bin";
            txtDestination.Text = @"\\zune-cj-dev\WenhuaZhao\bin";
            txtTarget.Text = "Microsoft.Amalga.Web.CategorizedContentViewer.dll";
        }
    }

    public delegate void SyncDelegate(string sourceDir, string destinationDir, string targetFile);

    public class FileSync
    {
        public static bool CanRun = true;

        public void Sync(string sourceDir, string destinationDir, string targetFile)
        {
            while (CanRun)
            {
                try
                {
                    FileInfo fiSource = new FileInfo(Path.Combine(sourceDir, targetFile));
                    fiSource.CopyTo(Path.Combine(destinationDir, targetFile), true);
                    Thread.Sleep(1000);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }
}
